//
//  SearchResultViewController.m
//  SportSocial
//
//  Created by yull on 15/1/28.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "SearchResultViewController.h"
#import "NearUserCell.h"
#import "NearGroupCell.h"
#import "PlaceInfoViewController.h"
#import "NearPlaceCell.h"
#import "UserNet.h"
#import "PlaceNet.h"
#import "GroupNet.h"
#import "UIScrollView+PullToRefresh.h"
#import "NDRefreshLoadMoreContainView.h"

#define Search_Page_Size    10

@interface SearchResultViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *searchTableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;

@end

@implementation SearchResultViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self addCommonBackButton];
    
    self.navigationItem.title = @"搜索";
    
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - Navibar_Height)];
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    self.searchTableView.backgroundColor = [UIColor clearColor];
    self.searchTableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.searchTableView];
    
    self.dataArray = [NSMutableArray array];
    [self loadData];
    
    @weakify(self);
    [self.searchTableView nd_addPullToRefreshWithActionHandler:^(id sender) {
        @strongify(self);
        self.currentPage = 0;
        [self loadData];
    } loadMoreWithActionHandler:^(id sender) {
        @strongify(self);
        [self loadData];
    }];
}

#pragma mark - Private
- (void)loadData
{
    switch (self.searchType) {
        case SearchTypeUser:
            [self searchUserWithName:self.searchText];
            break;
        case SearchTypeGroup:
            [self searchGroupWithName:self.searchText];
            break;
        case SearchTypePlace:
            [self searchPlaceWithName:self.searchText];
            break;
        default:
            break;
    }
}

#pragma mark - SearchNet

- (void)searchUserWithName:(NSString *)text
{
    [self showHUD];
    
    [UserNet searchUserWithName:text pageNumber:self.currentPage + 1 pageSize:Search_Page_Size successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self hideHUD];
        [self endLoad];
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *datadic = [responseObject objectForKey:@"data"];
            NSArray *listArray = [datadic objectForKey:@"list"];
            
            if (self.currentPage == 0) {
                [self.dataArray removeAllObjects];
            }
            
            self.currentPage = [[datadic objectForKey:@"pageNumber"] integerValue];
            self.totalPage = [[datadic objectForKey:@"totalPage"] integerValue];
            
            for (NSDictionary *dict in listArray) {
                [self.dataArray addObject:[NearUser userWithDict:dict]];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.currentPage == self.totalPage) {
                    ((NDRefreshLoadMoreContentView *)(self.searchTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                } else {
                    ((NDRefreshLoadMoreContentView *)(self.searchTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                }
                [self.searchTableView reloadData];
                
                if (!self.dataArray.count) {
                    [self showText:@"没有搜索到相关数据"];
                }
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hideHUD];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endLoad];
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)searchPlaceWithName:(NSString *)text
{
    [self showHUD];
    [PlaceNet searchPlaceWithName:text pageNumber:self.currentPage + 1 pageSize:Search_Page_Size successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hideHUD];
        [self endLoad];
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *datadic = [responseObject objectForKey:@"data"];
            NSArray *listArray = [datadic objectForKey:@"list"];
            
            if (self.currentPage == 0) {
                [self.dataArray removeAllObjects];
            }
            
            self.currentPage = [[datadic objectForKey:@"pageNumber"] integerValue];
            self.totalPage = [[datadic objectForKey:@"totalPage"] integerValue];
            
            for (NSDictionary *dict in listArray) {
                [self.dataArray addObject:[Place placeWithDict:dict]];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.currentPage == self.totalPage) {
                    ((NDRefreshLoadMoreContentView *)(self.searchTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                } else {
                    ((NDRefreshLoadMoreContentView *)(self.searchTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                }
                [self.searchTableView reloadData];
                
                if (!self.dataArray.count) {
                    [self showText:@"没有搜索到相关数据"];
                }
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hideHUD];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endLoad];
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)searchGroupWithName:(NSString *)text
{
    [GroupNet searchGroupWithName:text pageNumber:self.currentPage + 1 pageSize:Search_Page_Size successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hideHUD];
        [self endLoad];
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            
            NSDictionary *datadic = [responseObject objectForKey:@"data"];
            NSArray *listArray = [datadic objectForKey:@"list"];
            
            if (self.currentPage == 0) {
                [self.dataArray removeAllObjects];
            }
            
            self.currentPage = [[datadic objectForKey:@"pageNumber"] integerValue];
            self.totalPage = [[datadic objectForKey:@"totalPage"] integerValue];
            
            for (NSDictionary *dict in listArray) {
                [self.dataArray addObject:[NearGroup nearGroupWithDict:dict]];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.currentPage == self.totalPage) {
                    ((NDRefreshLoadMoreContentView *)(self.searchTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                } else {
                    ((NDRefreshLoadMoreContentView *)(self.searchTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                }
                [self.searchTableView reloadData];
                
                if (!self.dataArray.count) {
                    [self showText:@"没有搜索到相关数据"];
                }
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hideHUD];
        [self endLoad];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)endLoad
{
    [self.searchTableView nd_endLoadMore];
    [self.searchTableView nd_endRefreshing];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchType == SearchTypeUser) {
        return [NearUserCell nearCellDefaultHeight];
    }else if (self.searchType == SearchTypeGroup) {
        return [NearGroupCell nearGroupCellHeight];
    }else {
        return [NearPlaceCell placeCellHeight];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchType == SearchTypeUser) {
        static NSString *nearUserIdentifier = @"SearchUser";
        NearUserCell *nearUserCell = [tableView dequeueReusableCellWithIdentifier:nearUserIdentifier];
        
        if (!nearUserCell) {
            nearUserCell = [[NearUserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nearUserIdentifier];
//            nearUserCell.distanceLabel.hidden = YES;
        }
        
        NearUser *nearUser = [self.dataArray objectAtIndex:indexPath.row];
        
        [nearUserCell drawCellWithNearUser:nearUser];
        
        return nearUserCell;
    }else if (self.searchType == SearchTypeGroup) {
        static NSString *nearGroupIdentifier = @"SearchGroup";
        NearGroupCell *nearGroupCell = [tableView dequeueReusableCellWithIdentifier:nearGroupIdentifier];
        
        if (!nearGroupCell) {
            nearGroupCell = [[NearGroupCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nearGroupIdentifier];
//            nearGroupCell.distanceLabel.hidden = YES;
        }
        
        NearGroup *nearGroup = [self.dataArray objectAtIndex:indexPath.row];
        
        [nearGroupCell drawCellWithNearGroup:nearGroup];
        
        return nearGroupCell;
    }else {
        static NSString *nearPlaceIdentifier = @"NearPlace";
        NearPlaceCell *nearPlaceCell = [tableView dequeueReusableCellWithIdentifier:nearPlaceIdentifier];
        
        if (!nearPlaceCell) {
            nearPlaceCell = [[NearPlaceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nearPlaceIdentifier];
//            nearPlaceCell.distanceLabel.hidden = YES;
        }
        
        Place *place = [self.dataArray objectAtIndex:indexPath.row];
        
        [nearPlaceCell drawCellWithPlace:place];
        
        return nearPlaceCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchType == SearchTypePlace) {
        Place *place = [self.dataArray objectAtIndex:indexPath.row];
        
        PlaceInfoViewController *infoViewController = [[PlaceInfoViewController alloc] initWithPlace:place];
        infoViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:infoViewController animated:YES];
        
    }else if (self.searchType == SearchTypeUser) {
        NearUser *nearUser = [self.dataArray objectAtIndex:indexPath.row];
        
        UIViewController *infoViewController = [Interface createUserInfoViewControllerWithUserId:nearUser.userId userName:nearUser.name];
        [self.navigationController pushViewController:infoViewController animated:YES];
        
    }else {
        NearGroup *group = [self.dataArray objectAtIndex:indexPath.row];
        
        GroupInfoViewController *infoViewController = [[GroupInfoViewController alloc] initWithNearGroup:group];
        infoViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:infoViewController animated:YES];
    }
}

@end
